package games.cowsAndBulls;

/*
 * Here is the implements of Cows and bulls of course only business logic
 */

public class CowsAndBullsBusinessLogic implements ICowsAndBulls {
	private static final int MIN_NUMBERS = 3;
	private static final int MAX_NUMBERS = 5;
	private int[] numbers;
	private int[] numbersFromClient;

	public CowsAndBullsBusinessLogic(int numberOfSymbols) {
		setGameSettings(numberOfSymbols);
		generateRandomNumbers();
		numbersFromClient = new int[numbers.length];
	}

	private void generateRandomNumbers() {
		for (int i = 0; i < numbers.length; i++) {
			int random = (int) (Math.random() * 10);
			if (i == 0 && random == 0) {
				i--;
				continue;
			}

			boolean hasNumber = false;
			for (int j = 0; j <= i; j++) {
                if (random == numbers[j]) {
                	i--;
                	hasNumber = true;
                	break;
                }
            }
			if (!hasNumber)
				numbers[i] = random;
		}
	}

	@Override
	public void setGameSettings(int numberOfSymbols) {
		if (numberOfSymbols < 3)
			numbers = new int[MIN_NUMBERS];
		else if (numberOfSymbols > 5)
			numbers = new int[MAX_NUMBERS];
		else
			numbers = new int[numberOfSymbols];
	}
	
	//bug
	@Override
	public void getNumberFromClient(int numbersOfClient) {
		int divider = (int) Math.pow(10, (double) (numbersFromClient.length - 1));
        for (int i = 0; i < numbersFromClient.length; i++) {
                numbersFromClient[i] = numbersOfClient/divider;
                numbersOfClient%=divider;
                divider/=10;
        }
	}
	
	public boolean isNumberFromClientValid() {
		// test
		System.out.print("Generated number: ");
		for (int i = 0; i < numbers.length; i++) {
			System.out.print(numbers[i]);
		}
		System.out.print(" Length: " + numbers.length + "\nNumber from client: ");
		for (int i = 0; i < numbersFromClient.length; i++) {
			System.out.print(numbersFromClient[i]);
		}
		System.out.print(" Length: " + numbersFromClient.length + "\n");
		// end
		
		if (numbersFromClient.length != numbers.length)
			return false;
		
		for (int i = 0; i < numbersFromClient.length - 1; i++) {
			for (int j = i + 1; j < numbersFromClient.length; j++) {
				if (numbersFromClient[i] == numbersFromClient[j])
					return false;
			}
		}
		return true;
	}

	@Override
	public int getNumberOfCows() {
		int cows = 0;
		for (int i = 0; i < numbers.length; i++) {
			for (int j = 0; j < numbersFromClient.length; j++) {
				if (numbers[i] == numbersFromClient[j] && i != j)
					cows++;
			}
		}
		return cows;
	}

	@Override
	public int getNumberOfBulls() {
		int bulls = 0;
		for (int i = 0; i < numbers.length; i++) {
			if (numbersFromClient[i] == numbers[i])
				bulls++;
		}
		return bulls;
	}

	@Override
	public boolean isWin() {
		if (getNumberOfBulls() == numbers.length)
			return true;
		return false;
	}

}
